package com.ruoyi.user.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.user.domain.UserAnnouncement;
import com.ruoyi.user.domain.UserChatRecord;
import com.ruoyi.user.domain.ChatSession;
import com.ruoyi.user.domain.MessageAttachment;
import com.ruoyi.user.service.IUserAnnouncementService;
import com.ruoyi.user.service.IUserChatRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户消息中心Controller
 */
@RestController
@RequestMapping("/user/messages")
@Api(tags = "用户消息中心")
public class UserMessageController extends BaseController {
    @Autowired
    private IUserAnnouncementService userAnnouncementService;


    @Autowired
    private IUserChatRecordService userChatRecordService;

    /**
     * 2.52 获取消息通知
     */
    @GetMapping("/notifications")
    @ApiOperation("获取消息通知")
    public AjaxResult getNotifications() {
        try {
            Long customerId = SecurityUtils.getUserId();
            Long regionId = getCurrentUserRegionId();
            
            List<UserAnnouncement> notifications = userAnnouncementService.selectUserAnnouncements(customerId, regionId);
            int totalUnread = userAnnouncementService.selectUnreadUserAnnouncementCount(customerId, regionId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalUnread", totalUnread);
            result.put("notifications", notifications);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取消息通知失败", e);
            return AjaxResult.error("获取消息通知失败");
        }
    }

    /**
     * 2.53 获取消息会话列表
     */
    @GetMapping("/sessions")
    @ApiOperation("获取消息会话列表")
    public AjaxResult getSessions() {
        try {
            Long customerId = SecurityUtils.getUserId();
            List<ChatSession> sessions = userChatRecordService.selectUserSessions(customerId);
            return AjaxResult.success(sessions);
        } catch (Exception e) {
            logger.error("获取会话列表失败", e);
            return AjaxResult.error("获取会话列表失败");
        }
    }

    /**
     * 2.54 获取会话聊天记录
     */
    @GetMapping("/sessions/{sessionId}/history")
    @ApiOperation("获取会话聊天记录")
    public TableDataInfo getChatHistory(@PathVariable Long sessionId,
                                        @RequestParam(defaultValue = "1") Integer pageNum,
                                        @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            Long customerId = SecurityUtils.getUserId();

            // 获取会话信息
            ChatSession sessionInfo = userChatRecordService.selectSessionInfo(sessionId, customerId);
            if (sessionInfo == null) {
                return getDataTable(new ArrayList<>());
            }

            // 分页查询聊天记录
            startPage(); // 启动分页
            List<UserChatRecord> messages = userChatRecordService.selectUserChatRecordsBySession(sessionId, customerId);

            // 返回分页数据
            return getDataTable(messages);
        } catch (Exception e) {
            logger.error("获取聊天记录失败", e);
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 2.55 发送消息
     */
    @PostMapping("/sessions/{sessionId}/messages")
    @ApiOperation("发送消息")
    public AjaxResult sendMessage(@PathVariable Long sessionId,
                                  @RequestBody JSONObject requestBody) {
        try {
            Long customerId = SecurityUtils.getUserId();

            String content = requestBody.getString("content");
            Integer messageType = requestBody.getInteger("messageType");
            JSONObject attachmentJson = requestBody.getJSONObject("attachments");
            String relatedOrderId = requestBody.getString("relatedOrderId");
            Integer chatType = requestBody.getInteger("chatType"); // 新增参数
            Long targetId = requestBody.getLong("targetId"); // 新增参数

            // 验证消息内容不能为空
            if (content == null || content.trim().isEmpty()) {
                return AjaxResult.error(400, "消息内容不能为空");
            }

            if (messageType == null) {
                return AjaxResult.error(400, "消息类型不能为空");
            }

            MessageAttachment attachment = null;
            if (attachmentJson != null) {
                attachment = attachmentJson.toJavaObject(MessageAttachment.class);
            }

            // 检查会话是否存在
            ChatSession sessionInfo = userChatRecordService.selectSessionInfo(sessionId, customerId);
            if (sessionInfo == null) {
                // 会话不存在，需要创建新会话
                if (chatType == null || targetId == null) {
                    return AjaxResult.error(400, "新会话需要指定聊天类型和目标ID");
                }
                // 创建新会话
                Long newSessionId = userChatRecordService.getOrCreateSession(customerId, chatType, targetId);
                sessionId = newSessionId; // 使用新创建的会话ID
            }

            Map<String, Object> result = userChatRecordService.sendMessage(
                    sessionId, customerId, content, messageType, attachment, relatedOrderId);

            return AjaxResult.success("发送成功", result);
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return AjaxResult.error(500, "发送消息失败");
        }
    }

    /**
     * 2.511 标记消息为已读
     */
    @PostMapping("/sessions/{sessionId}/mark-read")
    @ApiOperation("标记消息为已读")
    public AjaxResult markMessagesAsRead(@PathVariable Long sessionId,
                                        @RequestBody JSONObject requestBody) {
        try {
            Long customerId = SecurityUtils.getUserId();
            
            Boolean readAll = requestBody.getBoolean("readAll");
            List<Long> chatIds = requestBody.getJSONArray("chatIds") != null ? 
                requestBody.getJSONArray("chatIds").toJavaList(Long.class) : null;
            
            Map<String, Object> result = userChatRecordService.markMessagesAsRead(
                sessionId, customerId, readAll, chatIds);
            
            return AjaxResult.success("标记已读成功", result);
        } catch (Exception e) {
            logger.error("标记消息为已读失败", e);
            return AjaxResult.error("标记消息为已读失败");
        }
    }

    /**
     * 2.57 清空聊天记录
     */
    @DeleteMapping("/sessions/{sessionId}")
    @ApiOperation("清空聊天记录")
    public AjaxResult clearChatHistory(@PathVariable Long sessionId) {
        try {
            Long customerId = SecurityUtils.getUserId();
            
            Map<String, Object> result = userChatRecordService.clearSessionMessages(sessionId, customerId);
            
            return AjaxResult.success("清空成功", result);
        } catch (Exception e) {
            logger.error("清空聊天记录失败", e);
            return AjaxResult.error("清空聊天记录失败");
        }
    }

    /**
     * 2.58 获取未读消息统计
     */
    @GetMapping("/unread-count")
    @ApiOperation("获取未读消息统计")
    public AjaxResult getUnreadCount() {
        try {
            Long customerId = SecurityUtils.getUserId();
            
            Map<String, Object> result = userChatRecordService.getUnreadMessageStats(customerId);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取未读消息统计失败", e);
            return AjaxResult.error("获取未读消息统计失败");
        }
    }

    /**
     * 创建新会话
     */
    @PostMapping("/sessions")
    @ApiOperation("创建新会话")
    public AjaxResult createSession(@RequestBody JSONObject requestBody) {
        try {
            Long customerId = SecurityUtils.getUserId();
            Integer chatType = requestBody.getInteger("chatType");
            Long targetId = requestBody.getLong("targetId");
            
            if (chatType == null || targetId == null) {
                return AjaxResult.error("参数错误");
            }
            
            Long sessionId = userChatRecordService.getOrCreateSession(customerId, chatType, targetId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("sessionId", sessionId);
            
            return AjaxResult.success("创建会话成功", result);
        } catch (Exception e) {
            logger.error("创建会话失败", e);
            return AjaxResult.error("创建会话失败");
        }
    }

    /**
     * 获取当前用户区域ID
     */
    private Long getCurrentUserRegionId() {
        // 这里需要根据实际情况获取用户区域ID
        // 暂时返回默认区域ID 1
        return 1L;
    }

    /**
     * 构建分页信息
     */
    private Map<String, Object> getPageInfo(Integer page, Integer size, Integer total) {
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("page", page);
        pageInfo.put("size", size);
        pageInfo.put("total", total);
        pageInfo.put("pages", (int) Math.ceil((double) total / size));
        return pageInfo;
    }
}